//
//  OneDoVC.swift
//  DollBuy
//
//  Created by 郑东喜 on 2016/11/22.
//  Copyright © 2016年 郑东喜. All rights reserved.
//

import UIKit
import WebKit


class OneDoVC : UIViewController,WKUIDelegate,WKScriptMessageHandler,WKNavigationDelegate {
    
    
    var webView: WKWebView!
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        self.navigationItem.title = "提现"
        
        var webView = WKWebView()
        
        //wkwebview相关配置
        
        //创建并配置WKWebView的相关参数
        //1.WKWebViewConfiguration:是WKWebView初始化时的配置类，里面存放着初始化WK的一系列属性；
        //2.WKUserContentController:为JS提供了一个发送消息的通道并且可以向页面注入JS的类，WKUserContentController对象可以添加多个scriptMessageHandler；
        //3.addScriptMessageHandler:name:有两个参数，第一个参数是userContentController的代理对象，第二个参数是JS里发送postMessage的对象。添加一个脚本消息的处理器,同时需要在JS中添加，window.webkit.messageHandlers.<name>.postMessage(<messageBody>)才能起作用。
        let configuration = WKWebViewConfiguration()
        let userContentController = WKUserContentController()
        
        //添加交互条目
        //分享到微信
        userContentController.add(self as WKScriptMessageHandler, name: "shareWeixinInfo")
        //微信支付
        userContentController.add(self as WKScriptMessageHandler, name: "weixinPay")
        
        //QQ分享
        userContentController.add(self as WKScriptMessageHandler, name: "qqshare")
        
        configuration.userContentController = userContentController
        
        let preferences = WKPreferences()
        preferences.javaScriptCanOpenWindowsAutomatically = true
        preferences.minimumFontSize = 10.0
        configuration.preferences = preferences
        
        webView.uiDelegate = self
        
        let rect = CGRect(x: 0, y: 35, width: SW, height: SH - 64 - 84)
        webView = WKWebView.init(frame: rect, configuration: configuration)
        
        //本地加载
        let htmlPath = Bundle.main.path(forResource: "WKWebViewMessageHandler", ofType: "html")

        DispatchQueue.main.async {
            do {
                let fileURL = try NSString.init(contentsOfFile: htmlPath!, encoding: String.Encoding.utf8.rawValue)
                let baseURL = NSURL.fileURL(withPath: htmlPath! as String)
                webView.loadHTMLString(fileURL as String, baseURL: baseURL)
            } catch  {
                
            }
            
        }
        
        //网页加载
//        http://yungou.ie1e.com/app/message_list.aspx?token=9327593088
//        DispatchQueue.main.async {
//            
//            let url = URL.init(string: mainPageURl)
//            
//            print(url)
//            webView.load(URLRequest(url: url!, cachePolicy: URLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: 2.0))
//        }
        
        view.addSubview(webView)
        
    }
    
    /**
     *  JS 调用 swift 时 webview 会调用此方法
     *
     *  @param userContentController  webview中配置的userContentController 信息
     *  @param message                JS执行传递的消息
     */
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
        print("\((#file as NSString).lastPathComponent):(\(#line))")
        
        let msg = message.name
        
        //将获取到的数据解析成字典
        let messageDic = message.body as! NSDictionary
        
        print(messageDic)
        
        if  msg == "shareWeixinInfo" {
            print("shareWeixinInfo")
            
            //解析取回的字典数据
            let titleStr = messageDic["title"] as! String
            let desc = messageDic["desc"] as! String
            let link = messageDic["link"] as! String
            let imgURL = messageDic["imgUrl"] as! String
            
            //测试吧
//            WXTool.shared.shareText()
//            WXTool.shared.shareText(title: titleStr, desc:desc, link: link, imgUrl: imgURL, shareType: 1)
            
            QQTool.shared.qqShare(title: titleStr, desc: desc, link: link, imgUrl: imgURL, type:QQApiURLTargetTypeAudio)
//            QQTool.shared.qqShare()
            
            
        }else if msg == "weixinPay" {
                print("weixinPay")
            
            let urlString = "http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php?plat=ios"
            
            postWithPath(path: urlString, paras: nil, success: { (response) in
                //判读返回值是否为空
                guard let dic = response as? NSDictionary else {
                    return
                }
                
                print(dic)
                
                WXTool.shared.sendWXPay(wxDict: dic)
                
                
            }) { (error) in
                print(error.localizedDescription)
            }

                
                let artController = UIAlertController(title: "支付", message: message.body as? String, preferredStyle: .alert)
                
                artController.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
//                self.present(artController, animated: true, completion: nil)
        } else if msg == "qqshare" {
//            print("qq share")
            
//            QQTool.shared.qqShare()
        }
    
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        //  NSString *hostname = navigationAction.request.URL.host.lowercaseString;
        let hostname = navigationAction.request.url?.host?.lowercased()
        print(hostname)
    }


}


